const inputs = document.querySelectorAll(".input")

function addcl() {
    let parent = this.parentNode.parentNode;
    parent.classList.add("focus")
}

function remcl() {
    let parent = this.parentNode.parentNode;
    if (this.value === "") {
        parent.classList.remove("focus")
    }
}

inputs.forEach(input => {
    input.addEventListener("focus", addcl);
    input.addEventListener("blur", remcl);
})
// dom操作
// 选择元素
var layer = $('.layer');
var layer_info = $('.layer div div');

// 请求部分
// 注册
$('.btn').click(function () {
    var info = $('form input');
    // 判断两次输入的密码是否相同
    if (info[1].value != info[2].value) {
        alert('两次输入的密码不一致')
        return
    }
    // 获取账号密码
    console.log(info[0].value, info[1].value, info[2].value, info[3].value);
    $.ajax({
        type: 'POST',
        url: '/api/users/',
        data: {
            'username': info[0].value,
            'password': info[1].value,
            'email': info[3].value
        },
        success: function (data) {
            console.log(data);
            console.log(typeof (data));   
            console.log(data.status);
            if (data.status == "error") {
                layer_info.attr('id', 'error');
                layer_info.append(`<i class="fas fa-tired"><span> 注册失败：${data.data}</span></i>`);
                layer.fadeIn(600);
                setTimeout(function () { layer.fadeOut(450); }, 1500);
                // 清楚layer_info的id和内容
                setTimeout(() => { layer_info.removeAttr('id'); layer_info.empty(); }, 3000);
                return null;
            }
            layer_info.attr('id', 'success');
            layer_info.append('<i class="fas fa-smile"><span> 注册成功</span></i>');
            layer.fadeIn(600);
            setTimeout(function () { layer.fadeOut(450); }, 1500);
            setTimeout(function () { window.location.href = '/'; }, 1500);
        },
        error: function (err) {
            console.log(err.responseText);
            // 失败
            layer_info.attr('id', 'error');
            errorMessage = err.responseText.match(/[\u4e00-\u9fa5]+/g);
            layer_info.append(`<i class="fas fa-tired"><span> 注册失败：${errorMessage}</span></i>`);
            layer.fadeIn(600);
            setTimeout(function () { layer.fadeOut(450); }, 1500);
            // 清楚layer_info的id和内容
            setTimeout(() => { layer_info.removeAttr('id'); layer_info.empty(); }, 3000);
        }
    });
    $('input').val('');
});